/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farmcode.core.runtime;

import com.farmcode.api.parser.ParserEngineAPI;
import com.farmcode.api.runtime.*;
import com.farmcode.api.runtime.database.DatabaseExplorerAPI;
import com.farmcode.api.types.DataTypesAPI;
import com.farmcode.api.types.TypeNotFoundException;
import com.farmcode.core.runtime.event.EventFactory;
import com.farmcode.core.runtime.event.ObjectsEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 *
 * @author oiprado
 */
@Remote(RuntimeServerAPI.class)
@Stateless(mappedName="ejb/runtimeServer")
public class RuntimeServerBean implements RuntimeServerAPI {

  
  @EJB
  ParserEngineAPI parserEngineAPI;
  @EJB(name="ejb/databaseExplorer",beanInterface=DatabaseExplorerAPI.class)
  DatabaseExplorerAPI databaseExplorerAPI;
  @EJB
  private DataTypesAPI dataTypesAPI;
  
  private BaseEvent event = null;

  @Override
  public Response getMetadata(FARMCodeContext context) throws RuntimeServerException{
    event = EventFactory.getInstance("-mt");
    event.setDatabaseExplorerAPI(databaseExplorerAPI);
    return excecute(context);
  }

  @Override
  public Response getColumn(FARMCodeContext context) throws RuntimeServerException{
    
      event = EventFactory.getInstance("-cl");
      event.setDatabaseExplorerAPI(databaseExplorerAPI);
    return excecute(context);
  }

  @Override
  public Response download(FARMCodeContext context) throws RuntimeServerException{
    event = EventFactory.getInstance("-d");
    return excecute(context);
  }
  
  @Override
  public Response clean(FARMCodeContext context) throws RuntimeServerException{
    event = EventFactory.getInstance("-cn");
    return excecute(context);
  }

  @Override
  public Response compile(FARMCodeContext context) throws RuntimeServerException{
    event = EventFactory.getInstance("-c");
    event.setParserEngineAPI(parserEngineAPI);
    return excecute(context);
  }

  private Response excecute(FARMCodeContext context) throws RuntimeServerException{
    if(event == null)
      throw new RuntimeServerException("Unknow event");
    try {
      context.put(FARMCodeContext.TYPES, dataTypesAPI.getTypes(context)) ;
    } catch (TypeNotFoundException ex) {
      Logger.getLogger(RuntimeServerBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return event.excecute(context);
  }

    @Override
    public Response testConection(FARMCodeContext context) throws RuntimeException {
        BaseResponse response = new BaseResponse();
        String message = databaseExplorerAPI.test(context);
        if(Boolean.parseBoolean(message)){
            response.addMessage("has been conected.");
        }else{
            response.addMessage("has been not conected.");
            response.addMessage(message);
        }
        return response;
    }
}
